package com.xxx.netty.eventloop;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * Client端关闭之后清理工作
 */
@Slf4j
public class CloseFutureClient {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        // ChannelFuture Client端启动入口
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        Channel channel = channelFuture.sync().channel();
        log.info("channel:{}", channel);
        // 模拟从console输入消息，发送给Server，当输入“q”时关闭Channel
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String input = scanner.nextLine();
                if("q".equals(input)) {
                    channel.close();
                    break;
                }
                channel.writeAndFlush(input);
            }
        }, "input").start();

        ChannelFuture closeFuture = channel.closeFuture();

        // 方式1：同步方式，主线程需要阻塞
//        log.info("waiting close...");
//        closeFuture.sync(); // 主线程需要阻塞
//        log.info("处理关闭之后的操作");

        // 2.方式2：异步方式，由NioEventLoopGroup中的线程来完成
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.info("处理关闭之后的操作");
                // 优雅地关闭客户端
                group.shutdownGracefully();
            }
        });
    }
}
